package com.compass.doctor.ui.home.fragment

import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager2.widget.ViewPager2
import com.compass.doctor.callback.OnDrugSelectClick
import com.compass.doctor.databinding.FragmentAllDrugsBinding
import com.compass.doctor.ui.home.adapter.DrugTabAdapter
import com.compass.doctor.ui.home.viewmodel.DrugViewModel
import com.compass.framework.adapter.ViewPage2FragmentAdapter
import com.compass.doctor.base.BaseVBFragment
import com.compass.framework.ext.toJson
import com.compass.framework.model.Drug
import com.compass.framework.model.DrugTabItem

/**
 * Description： 全部药品
 * Date:2023/12/7 10:18
 */
class AllDrugsFragment : BaseVBFragment<FragmentAllDrugsBinding>() {

    private var allDrug: MutableList<DrugTabItem> = ArrayList()
    private var isSearch: Boolean = false//是否是搜索
    //当前选中的position
    private var mCurrentSelectPosition = 0
    private var fragments: ArrayList<Fragment> = ArrayList()
    private lateinit var mTabAdapter: DrugTabAdapter
    private var mViewPagerAdapter: ViewPage2FragmentAdapter? = null

    private val drugViewModel: DrugViewModel by activityViewModels()
    override fun initView(view: View, savedInstanceState: Bundle?) {
        mBinding?.edtDrugName?.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                val keyWord = mBinding?.edtDrugName?.text.toString()
                if (isSearch) {
                    showLoading()
                    drugViewModel.getPharmacyInfo(keyWord)
                } else {
                    showToast("请输入搜索条件")
                }
            }
            false
        }
        mBinding?.edtDrugName?.addTextChangedListener {
            it?.let {
                isSearch = it.isNotEmpty()
                if (it.isEmpty())  setViewData(allDrug)
            }
        }
        mBinding?.refreshLayout?.setEnableRefresh(false)
        initTabRecyclerView()
        initViewPager2()
    }

    private fun initTabRecyclerView() {
        mTabAdapter = DrugTabAdapter()
        mBinding?.tabRecyclerView?.apply {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = mTabAdapter
        }
        mTabAdapter.onItemClickListener = { view: View, position: Int ->
            updateTabItem(position)
            mBinding?.viewPager2?.setCurrentItem(position, false)
        }
    }

    private fun initViewPager2() {
        activity?.let {
            mViewPagerAdapter = ViewPage2FragmentAdapter(childFragmentManager, lifecycle, fragments)
        }
        mBinding?.viewPager2?.apply {
            offscreenPageLimit = ViewPager2.SCROLL_STATE_SETTLING
            orientation = ViewPager2.ORIENTATION_VERTICAL
            registerOnPageChangeCallback(viewPager2Callback)
            adapter = mViewPagerAdapter
        }
    }


    override fun initData() {
        showLoading()
        drugViewModel.getPharmacyInfo()
        drugViewModel.drugTabLiveData.observe(this) { drugs ->
            dismissLoading()
            setViewData(drugs)
        }
    }

    private var onDrugItemClick = object : OnDrugSelectClick {
        override fun onDrugSelectCallBack(drug: Drug) {

        }
    }

    private fun setViewData(drugs: MutableList<DrugTabItem>?) {
        drugs?.let {
            //默认第一条选中
            it.firstOrNull()?.isSelected = true
            if (!isSearch) allDrug = it //不是搜索的情况下存存储全部数据
            mTabAdapter.setData(it)
            mTabAdapter.notifyDataSetChanged()
            it.forEachIndexed { index, item ->
//                if (fragments.isEmpty()) {
//                    var fragment = DrugFragment.newInstance(item.drugs?.toJson(true) ?: "", 1)
//                    fragments.add(index, fragment)
//                    fragment.setDrugItemClick(onDrugItemClick)
//                } else {
//                    var fragment = fragments[index] as DrugFragment
//                    fragment.setList(item.drugs)
//                }

                if (fragments.size < drugs.size) {
                    var fragment = DrugFragment.newInstance(item.drugs?.toJson(true) ?: "", 1)
                    fragments.add(index,fragment)
                    fragment.setDrugItemClick(onDrugItemClick)
                } else {
                    var fragment = fragments[index] as DrugFragment
                    if(fragment.isAdded){
                        fragment.setList(item.drugs)
                    }
                }
            }
            mViewPagerAdapter?.notifyItemRangeChanged(0, it.size)
        }
    }



    /**
     * 更新Tab状态
     * @param position 选择的item
     */
    private fun updateTabItem(position: Int) {
        mTabAdapter.setCurrentPosition(position)

        if (mCurrentSelectPosition != position) {
            //更新上一条item
            val selectedItem = mTabAdapter.getItem(mCurrentSelectPosition)
            selectedItem?.let { it.isSelected = false }
            //更新当前item
            val newItem = mTabAdapter.getItem(position)
            newItem?.let { it.isSelected = true }

            mCurrentSelectPosition = position
            mTabAdapter.notifyDataSetChanged()
            mBinding?.tabRecyclerView?.smoothScrollToPosition(position)
        }
    }

    /**
     * VIewPager2选择回调
     */
    private val viewPager2Callback = object : ViewPager2.OnPageChangeCallback() {
        override fun onPageSelected(position: Int) {
            updateTabItem(position)
        }
    }

    override fun onDestroyView() {
        mBinding?.viewPager2?.unregisterOnPageChangeCallback(viewPager2Callback)
        super.onDestroyView()
    }
}